package edu.unu.iist.ts2es.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HSet {
	
	private Map<Configuration, Set<Event>> h;
	private Map<Event,Event> replaceMap;
	
	public HSet(){
		h = new HashMap<Configuration, Set<Event>>();
		replaceMap = new HashMap<Event,Event>();
	}

	public void put(Configuration cfg, Set<Event> hset) {
		this.h.put(cfg, hset);
	}

	public Set<Event> getHSet(Set<Event> cf) {
		return this.h.get(cf);
	}

	public boolean contains(Set<Event> cf, String transName) {
		Iterator<Event> it = h.get(cf).iterator();
		while(it.hasNext()){
			Event event = it.next();
			if(event.getTransition().equals(transName)){
				return true;
			}
		}
		return false;
	}

	public Event getEvent(Set<Event> cf, String transName) {
		Iterator<Event> it = h.get(cf).iterator();
		while(it.hasNext()){
			Event event = it.next();
			if(event.getTransition().equals(transName)){
				return event;
			}
		}
		return null;
	}

	public void merge(Set<Event> cf, EventFactory ef) {
		Map<String,Event> teMap = new HashMap<String,Event>();
		Map<String,Boolean> isNew = new HashMap<String, Boolean>();
		Set<Event> hSet = h.get(cf);
		Object[] hSetArray = hSet.toArray();
		for(int i = 0; i < hSetArray.length; i++){	
			Event event = (Event) hSetArray[i];
			String trans = event.getTransition();
			if(!teMap.containsKey(trans)){
				teMap.put(trans, event);
				isNew.put(trans, false);
			}else{
				if(!isNew.get(trans)){
					Event newEvent = ef.creatNewEvent(trans);
					hSet.add(newEvent);
					hSet.remove(teMap.get(trans));
					replaceMap.put(teMap.get(trans),newEvent);
					teMap.put(trans, newEvent);
					isNew.put(trans, true);
				}
				hSet.remove(event);
				replaceMap.put(event,teMap.get(trans));
			}
		}
//		System.out.println("setMap:  " + setMap);	
		
		
	}

	public Map<Event, Event> getreplaceSet() {
		return this.replaceMap;
	}
}
